#include "mainwindow.h"
#include <QApplication>

#include "canthread.h"

#include <Qdebug>

int CANtype = 4;
int index = 0;


int baundRate =  250;
int devicCOM = 0;

#ifdef __cplusplus
extern "C" {
#endif
// C code...
#include <stdio.h>

#ifdef __cplusplus
}
#endif



int srun(void)
{
    VCI_CAN_OBJ precv[100];
    CANThread *canthread;
    char* str = "12345678\0";
    char recv_str[10] = {0};
    char print_str[256] = {0};
    int ret;
    int exit_with = -1;

    //atexit(deinit_dll);
    canthread = new CANThread();

    canthread->deviceType = CANtype;
    canthread->debicIndex = index;
    canthread->baundRate = baundRate;
    canthread->debicCom = devicCOM;
    bool dev = canthread->openCAN();
    if(dev == true)
         canthread->start();
    memset(precv, 0, sizeof(precv));
    canthread->sendDataToCanX(0, 0x22,(unsigned char*)str);
    ret = canthread->recvDataFromCanX(0, precv);
    if(ret <= 0)
    {
        return -1;
    }
    for (int i = 0; i < precv[0].DataLen; i++)
    {
        //printf("%x ", precv[0].Data[i]);
        if (str[i] != precv[0].Data[i])
            return -1;
    }
#if 0
    printf("id is %x\n", precv[0].ID);
    printf("DataLen is %d\n", precv[0].DataLen);
    for (int i = 0; i < precv[0].DataLen; i++)
    {
        printf("%x ", precv[0].Data[i]);
        recv_str[i] = precv[0].Data[i];
    }
    printf("\n");
#endif
    memset(precv, 0, sizeof(precv));
    canthread->sendDataToCanX(1, 0x22,(unsigned char*)str);
    canthread->recvDataFromCanX(1, precv);
    if(ret <= 0)
    {
        return -1;
    }
    for (int i = 0; i < precv[0].DataLen; i++)
    {
        //printf("%x ", precv[0].Data[i]);
        if (str[i] != precv[0].Data[i])
            return -1;
    }
    canthread->stop();
    canthread->closeCAN();


    return 0;
}


int main(int argc, char *argv[])
{
    int ret;
#if 0
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
#else
    //char *okk = "ok";
    //char *err = "err";

    ret = srun();
    if(ret == 0)
    {
        printf("{ \"test\": { \"mode\": \"can\", \"result\": \"ok\" } }");
    }else
    {
        printf("{ \"test\": { \"mode\": \"can\", \"result\": \"err\"} }");
    }

    //qDebug() << "Ret is "  << ret;

    return ret;
#endif
}
